<template>
  <a-result :title="title" v-if="showAsk">
    <template #extra>
      <a-button key="console" type="primary" @click="accept">接受</a-button>
    </template>
  </a-result>

  <a-result title="暂无会诊请求" v-if="!showAsk && state.patientId == 0">
    <template #icon>
      <smile-twoTone />
    </template>
  </a-result>

  <a-button type="primary" @click="addIllnessInfo" v-if="acceptFlag"
     style="margin-bottom: 10px;margin-left: 5px">添加病情记录</a-button
  >

  <a-modal
    :title="Title"
    v-model:visible="visibleAdd"
    :confirm-loading="confirmLoading"
    @ok="handleOk(state.illnessInfo)"
  >
    <a-form
      :model="state.illnessInfo"
      :label-col="{span: 4}"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="id" hidden>
        <a-input v-model:value="state.illnessInfo.id" style="width: 300px;" />
      </a-form-item>
      <a-form-item label="会诊编号">
        <a-input v-model:value="state.requestInfo.visitId" disabled="true" style="width: 300px;" />
      </a-form-item>
      <a-form-item label="疾病名称">
        <a-input v-model:value="state.illnessInfo.illness"  style="width: 300px;"/>
      </a-form-item>
      <a-form-item label="病因">
        <a-input v-model:value="state.illnessInfo.pathogeny"  style="width: 300px;"/>
      </a-form-item>
      <a-form-item label="医嘱">
        <a-input v-model:value="state.illnessInfo.advice"  style="width: 300px;"/>
      </a-form-item>
      <a-form-item label="就诊情况">
        <a-input v-model:value="state.illnessInfo.presentSituation" style="width: 300px;" />
      </a-form-item>
      <a-form-item label="用药">
        <a-input v-model:value="state.illnessInfo.medication" style="width: 300px;" />
      </a-form-item>
      <a-form-item label="过敏原">
        <a-input v-model:value="state.illnessInfo.allergy" style="width: 300px;" />
      </a-form-item>
    </a-form>
  </a-modal>

  <div class="space-align-container" v-if="acceptFlag">
    <div class="space-align-block">
      <a-space align="center">
        <a-list
          v-if="comments.length"
          :data-source="comments"
          :header="`${comments.length} ${
            comments.length > 1 ? 'replies' : 'reply'
          }`"
          item-layout="horizontal"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-comment
                :author="item.author"
                :avatar="item.avatar"
                :content="item.content"
                :datetime="item.datetime"
                style="justifycontent: 'flex-end'; minwidth: 100"
              />
            </a-list-item>
          </template>
        </a-list>
        <a-comment>
          <template #avatar>
            <a-avatar
              src="https://images.nweb.top/touxiang1.png"
              alt="Han Solo"
            />
          </template>
          <template #content>
            <a-form-item>
              <a-textarea v-model:value="value" :rows="4" />
            </a-form-item>
            <a-form-item>
              <a-button
                html-type="submit"
                :loading="submitting"
                type="primary"
                @click="handleSubmit"
              >
                发送消息
              </a-button>
            </a-form-item>
          </template>
        </a-comment>

        <span class="mock-block">
          <a-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            show-line
            :tree-data="state.cureHistory"
            @select="selectNode"
          >
            <template #switcherIcon="{ switcherCls }"
              ><down-outlined :class="switcherCls"
            /></template>
          </a-tree>
        </span>
      </a-space>
    </div>
  </div>

  <a-drawer
    width="640"
    placement="right"
    :closable="false"
    :visible="visible"
    @close="onClose"
  >
    <p :style="pStyle">检查结果</p>
    <div v-if="checkOutList.length === 0">暂无检查结果</div>
    <div v-else>--------------------------------------------------------------------------------------------------</div>
    <div v-for="item in checkOutList" v-bind:key="item">
      <br />
      <a-row>
        <a-col :span="12"> 检查编号:{{ item.id }} </a-col>
        <a-col :span="12"> 项目:{{ item.project }} </a-col>
        <a-col :span="12"> 结果:{{ item.result }} </a-col>
        <a-col :span="12"> 检查时间:{{ item.createTime }} </a-col>
        <div v-if="item.isImage === 1">
          图片:
          <div v-for="img in item.image" v-bind:key="img">
            <a-col :span="12"> <a-image :width="200" :src="img" /> </a-col>
          </div>
        </div>
        <div v-else>无检查图片</div>
      </a-row>
      <br />
      <div>--------------------------------------------------------------------------------------------------</div>
    </div>

    <a-divider />
  </a-drawer>
</template>
<script>
import {
  defineComponent,
  ref,
  onMounted,
  reactive,
  resolveComponent,
  onUnmounted,
} from "vue";
import { DownOutlined } from "@ant-design/icons-vue";
import { SmileTwoTone } from "@ant-design/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import {
  reqGetCureCheckOutByCureId,
  reqGetHistoryCureByPatientId,
  reqGetCureById,
  reqAddIllnessInfo,
  // reqUpdateVisitInfoById,
} from "../api/index";
import { useStore } from "vuex";
dayjs.extend(relativeTime);
export default defineComponent({
  components: {
    DownOutlined,
    SmileTwoTone,
  },
  setup() {
    const Title = ref('')
    const store = useStore();
    const comments = ref([]);
    const submitting = ref(false);
    const value = ref("");
    const title = ref("");
    const showAsk = ref(false);
    const confirmLoading = ref(false);
    const acceptFlag = ref(false);
    var socket = null;
    const visible = ref(false);
    const visibleAdd = ref(false);
    const heartBeat = ref(0);
    const heartList = reactive([]);
    const modalText = ref("Content of the modal");
    const pStyle = {
      fontSize: "16px",
      color: "rgba(0,0,0,0.85)",
      lineHeight: "24px",
      display: "block",
      marginBottom: "16px",
    };
    const checkOutList = ref({});
    const state = reactive({
      toInfo: {},
      cureHistory: [],
      patientId: 0,
      cureId: 0,
      requestInfo: {},
      illnessInfo: {},
      baseInfo:{}
    });

    const addIllnessInfo = () => {
      visibleAdd.value = true;
      Title.value = '添加病情记录';
    };

    const handleOk = async (illnessInfo) => {
      modalText.value = "please wait for sometime";
      confirmLoading.value = true;
      illnessInfo.visitId = state.requestInfo.visitId;
      let result = await reqAddIllnessInfo(illnessInfo);
      if (result.code === 200) {
        visibleAdd.value = false;
        confirmLoading.value = false;
        let result1 = await reqGetHistoryCureByPatientId(state.patientId);
        state.cureHistory = result1["data"];
        state.illnessInfo = {};
      }
    };

    const selectNode = async (object, e) => {
      if (e.node.title.substring(0, 4) == "诊疗编号") {
        let cureId = e.node.title.substring(5, e.node.title.indexOf(","));
        let result = await reqGetCureCheckOutByCureId(cureId);
        checkOutList.value = result["data"];
        for (var i = 0; i < checkOutList.value.length; i++) {
          var image = checkOutList.value[i].image;
          if (image != "" && image != null) {
            checkOutList.value[i].image = image.split(";");
            checkOutList.value[i].image.pop();
          }
        }
        visible.value = true;
      }
    };

    onMounted(async () => {
      //判断当前浏览器是否支持websocket
      if (window.WebSocket) {
        //go on
        socket = new WebSocket(process.env.VUE_APP_SOCKET_URL);
        //socket = new WebSocket("ws://localhost:9000/socket");
        socket.onopen = websocketonopen;
        socket.onmessage = websocketonmessage;
        socket.onerror = websocketonerror;
        socket.onclose = websocketclose;
      } else {
        alert("当前浏览器不支持websocket");
      }

      onUnmounted(() => {
        socket.close();
        heartList.forEach((item) => {
          clearInterval(item);
        });
      });

      state.toInfo = store.state.toInfo;

      state.requestInfo.visitId = store.state.visitId

      let result = await reqGetCureById(store.state.cureId);
      if (result["data"] != null) {
        state.cureId = store.state.cureId;
        state.patientId = result["data"].patientId;
        let result1 = await reqGetHistoryCureByPatientId(state.patientId);
        state.cureHistory = result1["data"];
        acceptFlag.value = true;
      }
    });
    // Websoket连接成功事件
    const websocketonopen = () => {
      console.log("WebSocket连接成功", resolveComponent);
      let userId = sessionStorage.getItem("userId");
      socket.send(`{"code":0,"id":${userId}}`);
      heartBeat.value = setInterval(() => {
        socket.send(`{"code":0,"id":${userId}}`);
        console.log("ping");
      }, 15000);
      heartList.push(heartBeat.value);
    };
    // Websoket接收消息事件
    const websocketonmessage = (res) => {
      let result = JSON.parse(res.data);
      console.log("接收消息事件", result);
      if (result.resCode == 1) {
        console.log("收到", result.chatMessage, state.toInfo.name);
        heartBeat.value = setTimeout(() => {
          comments.value = [
            {
              author: state.toInfo.name,
              avatar: "https://images.nweb.top/touxiang2.png",
              content: result.chatMessage,
              datetime: dayjs().fromNow(),
            },
            ...comments.value,
          ];
        }, 1000);
      } else if (result.resCode != -1 && store.state.isRequest) {
        store.state.isRequest = false;
        socket.send(`{
            "code":2,
            "requestId":${sessionStorage.getItem("userId")},
            "expertId": ${state.toInfo.id},
            "cureId":${store.state.cureId},
            "visitId":${store.state.visitId}
        }`);
      } else if (result.resCode == 3) {
        showAsk.value = true;
        title.value = "医生编号:" + result.requestId + "请求远程会诊";
        state.requestInfo = result;
      }
    };
    // Websoket连接错误事件
    const websocketonerror = (res) => {
      console.log("连接错误", res);
    };
    // Websoket断开事件
    const websocketclose = (res) => {
      console.log("断开连接", res);
    };

    const handleSubmit = () => {
      if (!value.value) {
        return;
      }

      submitting.value = true;
      setTimeout(() => {
        submitting.value = false;
        console.log("发送消息", value.value, "id", state.toInfo.id);
        socket.send(`{
                      "code":1,
                      "toId":${state.toInfo.id},
                      "chatMessage":"${value.value}"
                    }`);
        comments.value = [
          {
            author: sessionStorage.getItem("name"),
            avatar: "https://images.nweb.top/touxiang1.png",
            content: value.value,
            datetime: dayjs().fromNow(),
          },
          ...comments.value,
        ];
        value.value = "";
      }, 1000);
    };

    const accept = async () => {
      let result = await reqGetCureById(state.requestInfo.cureId);
      state.patientId = result["data"].patientId;
      state.toInfo.id = state.requestInfo.requestId;
      //state.toInfo.name = "expert"
      let result1 = await reqGetHistoryCureByPatientId(state.patientId);
      state.cureHistory = result1["data"];
      showAsk.value = false;
      acceptFlag.value = true;
      // let result2 = await reqUpdateVisitInfoById({
      //   id: state.requestInfo.visitId,
      //   doctorId: sessionStorage.getItem("userId"),
      // });
    };

    const expandedKeys = ref(["0-0-0"]);
    const selectedKeys = ref([]);

    const onClose = () => {
      visible.value = false;
    };

    return {
      Title,
      comments,
      submitting,
      value,
      handleSubmit,
      socket,
      state,
      expandedKeys,
      selectedKeys,
      selectNode,
      store,
      showAsk,
      title,
      accept,
      acceptFlag,
      visible,
      onClose,
      pStyle,
      checkOutList,
      addIllnessInfo,
      handleOk,
      visibleAdd,
      modalText,
      confirmLoading,
      heartBeat,
      heartList,
    };
  },
});
</script>
<style scoped>
.space-align-container {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}
.space-align-block {
  margin: 8px 4px;
  border: 1px solid #40a9ff;
  padding: 4px;
  flex: none;
}
.space-align-block .mock-block {
  display: inline-block;
  padding: 32px 8px 16px;
  background: rgba(150, 150, 150, 0.2);
}
</style>
